/*
 * @Author: thepoy
 * @Email: thepoy@163.com
 * @File Name: es.go
 * @Created: 2021-05-07 21:31:38
 * @Modified: 2021-05-08 13:46:13
 */

package rocketmq

import (
	"core/es"
	"fmt"
	"log"

	"github.com/elastic/go-elasticsearch/v8"
)

const (
	indexName string = "canal_es"
)

var (
	client *elasticsearch.Client
	store  *es.Store
)

func init() {
	client, err = elasticsearch.NewDefaultClient()
	if err != nil {
		log.Fatalln(err)
	}

	config := es.StoreConfig{Client: client, IndexName: indexName}
	store, err = es.NewStore(config)
	if err != nil {
		log.Fatalln(err)
	}
}

func setupIndex() error {
	mapping := `{
        "mappings": {
            "properties": {
                "id":         { "type": "keyword" },
                "title":      { "type": "text", "analyzer": "ik_max_word", "search_analyzer": "ik_smart" },
                "content":        { "type": "text", "analyzer": "ik_max_word", "search_analyzer": "ik_smart" },
                "created_date": { "type": "text", "analyzer": "english" }
            }
        }
    }`

	return store.CreateIndex(mapping)
}

func storeDocument(data map[string]interface{}) error {
	return store.Create(data)
}

func updateDocument(id string, newData map[string]string) (bool, error) {
	return store.Update(id, newData)
}

func existsDocument(id string) (bool, error) {
	ok, err := store.Exists(id)
	if err != nil {
		return false, fmt.Errorf("store: %s", err)
	}
	return ok, nil
}

func deleteDocument(id string) error {
	return store.Delete(id)
}
